package com.ash.dao.impl;

import com.ash.dao.IDao;
import com.ash.util.ConnectionUtil;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;


/**
 * @encoding : UTF-8
 * @Time : 2020/12/4 10:55
 * @Author : Chen Chao
 * @File : connection.com.ash.dao.impl.IDaoImpl.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class IDaoImpl<T> implements IDao<T> {
    public  String addSql(T t){
        Class<?> tClass = t.getClass();
        String sql="insert into "+tClass.getSimpleName().toLowerCase();
        HashMap<String, String> map = new HashMap<>();
        Field[] fields = tClass.getDeclaredFields();

        /*遍历字段*/
        for (Field field : fields) {
            try {
                String name = field.getName();
                field.setAccessible(true);
                Object o = field.get(t);
                System.out.println(o);
                String value= o.toString();
                field.setAccessible(false);

                if(field.getType()==String.class){
                    value="'"+value+"'";
                }
                map.put(name,value);
            } catch ( IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        String values = Arrays.toString(new Collection[]{map.values()});
        String keys = Arrays.toString(new Set[]{map.keySet()});
        values=values.substring(2,values.length()-2);
        keys=keys.substring(2,keys.length()-2);
        return sql+"("+keys+") value ("+values+")";
    }
    @Override
    public  boolean add(T t) {
        Connection connection = null;
        Statement statement=null;
        try {
            connection = ConnectionUtil.getConnection();
            statement = Objects.requireNonNull(connection).createStatement();
            String s = addSql(t);
            System.out.println(s);
            statement.executeUpdate(s);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,statement,null);
        }
        return false;
    }

    @Override
    public T select(T t) {
        return null;
    }

    @Override
    public List<T> selectAll(Class<T> tClass) {
        String sql="Select * from "+tClass.getSimpleName().toLowerCase();
        return null;
    }

    @Override
    public  boolean delete(T t) {

        return false;
    }

    @Override
    public boolean modify(T t) {
        return false;
    }
}
